﻿using System;
using System.Collections.Generic;
using System.IO;
using Core;
using Core.Interfaces;
using Core.IocHelpers;
using DataXml.CommunityFiles;

namespace DataXml
{
  ///<summary>
  ///  Import a ver.1 community file
  ///</summary>
  [AutoRegister]
  public class CommunityImporter : ICommunityImporter
  {
    private string _filePath;

    ///<summary>
    ///</summary>
    public CommunityImporter()
    {
      ErrorMessages = new List<string>();
    }

    public ICommunity Community { get; private set; }

    public List<string> ErrorMessages { get; private set; }

    public bool Successful { get; private set; }

    public bool SourceExists { get; set; }

    internal CommunityImporter AttachTo(string filePath)
    {
      SourceExists = File.Exists(filePath);
      if (SourceExists)
      {
        _filePath = filePath;
      }
      else
      {
        ErrorMessages.Add("File not found: " + filePath);
        _filePath = string.Empty;
      }
      return this;
    }

    internal CommunityImporter ImportData()
    {
      if (SourceExists)
      {
        try
        {
            Community = XmlHelper.ReadCommunity(_filePath);
            Successful = true;
        }
        catch (Exception ex)
        {
          Community = null;
          Successful = false;
          ErrorMessages.Add("Error loading file. " + ex.AllMessages());
        }
      }

      return this;
    }

    private static MemoryStream ModifyContent(TextReader file)
    {
      var content = file.ReadToEnd();

      //content = content.Replace("Pre-Youth", "PreYouth");

      var stream = new MemoryStream();
      var writer = new StreamWriter(stream);
      writer.Write(content);
      writer.Flush();

      stream.Position = 0;
      return stream;
    }

    ///<summary>Load the XML. Check <see cref="Successful"/> and <see cref="ErrorMessages"/> after loading.
    ///</summary>
    ///<param name="communityFilePath"></param>
    ///<returns></returns>
    public void ImportCommunity(string communityFilePath)
    {
      AttachTo(communityFilePath).ImportData();
    }
  }
}